package com.inxedu.os.edu.controller.main;

import com.asual.lesscss.LessEngine;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.inxedu.os.common.controller.BaseController;
import com.inxedu.os.common.util.ObjectUtils;
import com.inxedu.os.common.util.SingletonLoginUtils;
import com.inxedu.os.common.util.StringUtils;
import com.inxedu.os.edu.constants.enums.WebSiteProfileType;
import com.inxedu.os.edu.entity.system.SysUser;
import com.inxedu.os.edu.entity.webpage.Webpage;
import com.inxedu.os.edu.entity.webpagetemplate.WebpageTemplate;
import com.inxedu.os.edu.entity.website.WebsiteProfile;
import com.inxedu.os.edu.service.webpage.WebpageService;
import com.inxedu.os.edu.service.webpagetemplate.WebpageTemplateService;
import com.inxedu.os.edu.service.website.WebsiteProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;

import static com.inxedu.os.edu.constants.enums.WebSiteProfileType.defaultTemplateId;

/**
 * @author www.inxedu.com
 *
 */
@Controller
@RequestMapping("/admin/main")
public class MainController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(MainController.class);
	private static String mainPage = getViewPath("/admin/main/main");
	private static String mainIndexPage = getViewPath("/admin/main/index");
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private WebpageService webpageService;
	@Autowired
	private WebpageTemplateService webpageTemplateService;

	/**
	 * 进入操作中心
	 * @param request
	 * @return ModelAndView
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping()
	public ModelAndView mainPage(HttpServletRequest request){
		ModelAndView model = new ModelAndView();
		try{
			SysUser sysuser = SingletonLoginUtils.getLoginSysUser(request);
			model.setViewName(mainPage);
			model.addObject("sysuser", sysuser);


			Map<String,Object> color = (Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.color.toString()).get(WebSiteProfileType.color.toString());
			model.addObject("color",color.get("color"));
			Map<String,String> defaultTemplateIdMap = (Map<String,String>)websiteProfileService.getWebsiteProfileByType(defaultTemplateId.toString()).get(defaultTemplateId.toString());
			model.addObject("defaultTemplateId",Integer.parseInt(defaultTemplateIdMap.get("defaultTemplateId")+""));
            if (StringUtils.isNotEmpty(request.getParameter("webPageUrl"))) {
                Webpage webpage=new Webpage();
                webpage.setPublishUrl(request.getParameter("webPageUrl"));
                List<Webpage> webpageList=webpageService.queryWebpageList(webpage);
                if (ObjectUtils.isNotNull(webpageList)){
                    webpage=webpageList.get(0);
                    model.addObject("webPageUrl",webpage.getPublishUrl());
                    model.addObject("webpage",webpage);
                }
            }else {
                Webpage webpage=new Webpage();
                webpage.setPublishUrl("/index.html");
                List<Webpage> webpageList=webpageService.queryWebpageList(webpage);
                if (ObjectUtils.isNotNull(webpageList)){
                    webpage=webpageList.get(0);
                    model.addObject("webPageUrl",webpage.getPublishUrl());
                    model.addObject("webpage",webpage);
                }
            }

		}catch (Exception e) {
			model.setViewName(this.setExceptionRequest(request, e));
			logger.error("mainPage()--error",e);
		}
		return model;
	}
	



	/**
	 * 后台操作中心初始化首页
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("/index")
	public ModelAndView mainIndex(HttpServletRequest request){
		ModelAndView model = new ModelAndView();
		try{
			model.setViewName(mainIndexPage);
			
			Map<String,Object> color = (Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.color.toString()).get(WebSiteProfileType.color.toString());
			model.addObject("color",color.get("color"));
			if (StringUtils.isNotEmpty(request.getParameter("webPageUrl"))) {
				Webpage webpage=new Webpage();
				webpage.setPublishUrl(request.getParameter("webPageUrl"));
				List<Webpage> webpageList=webpageService.queryWebpageList(webpage);
				if (ObjectUtils.isNotNull(webpageList)){
					webpage=webpageList.get(0);
					model.addObject("webPageUrl",webpage.getPublishUrl());
					model.addObject("webpage",webpage);
				}
			}

		}catch (Exception e) {
			model.setViewName(this.setExceptionRequest(request, e));
			logger.error("mainIndex()---error",e);
		}
		return model;
	}
	
	/**
	 * 访问权限受限制跳转
	 * @return ModelAndView
	 */
	@RequestMapping("/notfunction")
	public ModelAndView notFunctionMsg(){
		ModelAndView model = new ModelAndView();
		model.addObject("message", "对不起，您没有操作权限！");
		model.setViewName("/common/notFunctonMsg");
		return model;
	}
	/**
	 * 后台头部页面
	 */
	@RequestMapping("/header")
	public String mainHeader(HttpServletRequest request){
		try{

		}catch (Exception e) {
			logger.error("mainHeader()---error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/main/header");
	}
	/**
	 * 后台头部页面
	 */
	@RequestMapping("/left")
	public String mainLeft(HttpServletRequest request){
		try{
			Webpage webpage=new Webpage();
			webpage.setPublishUrl(request.getParameter("webPageUrl"));
			List<Webpage> webpageList=webpageService.queryWebpageList(webpage);
			if (ObjectUtils.isNotNull(webpageList)){
				webpage=webpageList.get(0);

				WebpageTemplate webpageTemplate=new WebpageTemplate();
				webpageTemplate.setEffective(2);
				webpageTemplate.setPageId(webpage.getId());
				//进入页面前 删除 之前添加为发布的模板
				webpageTemplateService.delWebpageTemplate(webpageTemplate);

				webpageTemplate=new WebpageTemplate();
				webpageTemplate.setPageId(webpage.getId());
				List<WebpageTemplate> webpageTemplateList=webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
				request.setAttribute("webpageTemplateList", webpageTemplateList);
                request.setAttribute("webpage",webpage);
            }
		}catch (Exception e) {
			logger.error("mainLeft()---error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/main/left");
	}

	/**
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("/addTemplate")
	public String addTemplate(HttpServletRequest request,Long webpageId){
		try {
			WebpageTemplate webpageTemplate = new WebpageTemplate();
			webpageTemplate.setPageId(webpageId);
			webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
			List<WebpageTemplate> webpageTemplateList = webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
			request.setAttribute("webpageId",webpageId);
			List templateUrlArr = new ArrayList();
			for (WebpageTemplate webpageTemplate1:webpageTemplateList){
				templateUrlArr.add(webpageTemplate1.getTemplateUrl());
			}
			request.setAttribute("templateUrlArr",templateUrlArr);
		}catch (Exception e){
			logger.error("addTemplate()---error",e);
			return this.setExceptionRequest(request, e);
		}
		return getViewPath("/admin/main/addTemplate");
	}
	/** 修改主题色 */
	@RequestMapping("/updColor")
	public String updateTheme(HttpServletRequest request) {
		String color = request.getParameter("color");
		//获得项目根目录
		String strDirPath = request.getSession().getServletContext().getRealPath("/")+"/template/templet1/";
		//读取字符串
		StringBuffer sb = new StringBuffer();
		//当前读取行数
		int rowcount = 1 ;
		//要修改的行数
		int updaterowcount = 2 ;
		FileReader fr;
		try {
			String path = strDirPath+"css/color.less";
			fr = new FileReader(path);
			BufferedReader br = new BufferedReader(fr);
			String line = br.readLine();
			while (line != null) {
				if(rowcount==updaterowcount&&StringUtils.isNotEmpty(color)){
					sb.append("@mColor:"+color+";");
				}else{
					sb.append(line);
				}
				line = br.readLine();
				rowcount++;
			}
			br.close();
			fr.close();
			LessEngine engine = new LessEngine();
			FileWriter fw = new FileWriter(strDirPath+"css/color.css");
			fw.write(engine.compile(sb.toString()));
			fw.close();
			JsonParser jsonParser = new JsonParser();
			Map<String, String> map = new HashMap<String, String>();
			map.put("color", color);
			// 将map转化json串
			JsonObject jsonObject = jsonParser.parse(gson.toJson(map)).getAsJsonObject();
			if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
				WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
				websiteProfile.setType(WebSiteProfileType.color.toString());
				websiteProfile.setDesciption(jsonObject.toString());
				websiteProfileService.updateWebsiteProfile(websiteProfile);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/admin/main";
	}
}